package cn.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.common.ExceResult;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.entity.loan.LoanUserEntity;
import cn.kpi.entity.loan.LoanUserListEntity;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.entity.vtiondpline.VtDpItemEntity;
import cn.kpi.entity.vtiondpline.VtDpUserEntity;
import cn.kpi.entity.vtiondpline.VtDpUserListEntity;
import cn.kpi.entity.vtiondpline.VtDpUserLogEntity;
import cn.kpi.service.loan.ILoanUserService;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.sys.IUserService;

@Controller
@RequestMapping("loanuser")
public class LoanUserController extends BaseController {
    @Autowired
    private ILoanUserService iLoanUserService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IOrgService iOrgService;

    @RequestMapping("/loan_tb_list")
    public String LoanTbList(Model model) {
        try {
            //List<OrgEntity> orglst = iOrgService.GetOrgList();
//			String where=this.GetLoginUserOrgidWhereForOrg();
//			List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
//			for (int i = 0; i < orglst.size(); i++) {
//				String html="";
//				for(int j=0;j<orglst.get(i).getLevel();j++){
//					html+="&#12288;";
//				}
//				orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
//			}
//			model.addAttribute("orglst", orglst);
            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);
        } catch (Exception ex) {

        }
        return "loan/loan_tb_list";
    }

    @RequestMapping(value = "/loan_tb_edit")
    public String UserLoanEdit(Model model, Long loanid) {
        try {
            String whereuser = this.GetLoginUserForUserListWhere();
            List<UserEntity> userlst = iUserService.GetUserListByWhere(whereuser);
            model.addAttribute("userlst", userlst);

            //String where=this.GetLoginUserOrgidWhereForOrg();
            String where = "";
            List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
            for (int i = 0; i < orglst.size(); i++) {
                String html = "";
                for (int j = 0; j < orglst.get(i).getLevel(); j++) {
                    html += "&#12288;";
                }
                orglst.get(i).setOrgname(html + orglst.get(i).getOrgname());
            }
            model.addAttribute("orglst", orglst);

            LoanUserListEntity entity = new LoanUserListEntity();
            if (loanid > 0) {
                entity = iLoanUserService.GetUserLoanByLoanid(loanid);
            } else {
                entity.setLoanid(0L);
            }
            model.addAttribute("entity", entity);

        } catch (Exception ex) {

        }
        return "loan/loan_tb_edit";
    }

    @RequestMapping("/loan_gd_list")
    public String LoanGdList(Model model) {
        try {
//			String where=this.GetLoginUserOrgidWhereForOrg();
//			List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
//			for (int i = 0; i < orglst.size(); i++) {
//				String html="";
//				for(int j=0;j<orglst.get(i).getLevel();j++){
//					html+="&#12288;";
//				}
//				orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
//			}
//			model.addAttribute("orglst", orglst);
            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);
            if (this.GetLoginUser().getRealname().contains("开发")) {

                model.addAttribute("isadmin", true);


            } else {
                model.addAttribute("isadmin", false);

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "loan/loan_gd_list";
    }

    @RequestMapping(value = "/loan_gd_edit")
    public String UserLoanGdEdit(Model model, Long userid, int status, Long loanid, Long loanorgid) {
        try {
            UserEntity userentity = iUserService.GetUserById(userid);
            model.addAttribute("userentity", userentity);
            model.addAttribute("status", status);
            model.addAttribute("loanid", loanid);
            model.addAttribute("loanorgid", loanorgid);
        } catch (Exception ex) {

        }
        return "loan/loan_gd_edit";
    }

    @RequestMapping("/loan_js_list")
    public String LoanJsList(Model model, @RequestParam(value = "Dq", required = false) String Dq) {
        try {
            //System.out.println();
//			String where=this.GetLoginUserOrgidWhereForOrg();
//			List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
//			for (int i = 0; i < orglst.size(); i++) {
//				String html="";
//				for(int j=0;j<orglst.get(i).getLevel();j++){
//					html+="&#12288;";
//				}
//				orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
//			}
//			model.addAttribute("orglst", orglst);

            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);

            int dqflag = 0;
            if (Dq != null && Dq.length() > 0) {
                dqflag = Integer.parseInt(Dq);
            }
            model.addAttribute("dqflag", dqflag);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "loan/loan_js_list";
    }

    @RequestMapping(value = "/loan_js_edit")
    public String UserLoanJsEdit(Model model, Long userid, int status, Long loanid, Long loanorgid) {
        try {
            UserEntity userentity = iUserService.GetUserById(userid);
            model.addAttribute("userentity", userentity);
            model.addAttribute("status", status);
            model.addAttribute("loanid", loanid);
            model.addAttribute("loanorgid", loanorgid);
        } catch (Exception ex) {

        }
        return "loan/loan_js_edit";
    }


    @RequestMapping("/loan_ck_list")
    public String LoanCkList(Model model) {
        try {
            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "loan/loan_ck_list";
    }

    @RequestMapping(value = "/add_loanuser")
    public String AddLoanUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            Long loanid = Long.parseLong(request.getParameter("loanid"));
            String struserid = request.getParameter("userid");
            String strorgid = request.getParameter("orgid");
            String strbegintime = request.getParameter("begintime");
            String strendtime = request.getParameter("endtime");
            String loandes = request.getParameter("loandes");
            Long orgid = Long.parseLong(strorgid);
            Long userid = Long.parseLong(struserid);
            UserEntity user = this.GetUserById(userid);//拿到保存用户详细信息

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            LoanUserEntity entity = new LoanUserEntity();
            entity.setBegintime(sdf.parse(strbegintime));
            entity.setEndtime(sdf.parse(strendtime));
            entity.setLoandes(loandes);
            entity.setLoanorgid(orgid);
            entity.setStatus(0);
            entity.setUserid(userid);
            entity.setByuserid(this.GetLoginUserId());

            entity.setSzdw(user.getSzdw());
            entity.setSzdwname(user.getOrgname());
            entity.setUserstatus(user.getUserstatus());
            entity.setRsgxszdw(user.getRsgxszdw());
            entity.setRsgxszdwname(user.getRsgxorgname());

            int iResult = 0;
            if (loanid > 0) {
                entity.setLoanid(loanid);
                iResult = iLoanUserService.UpdateLoanUserEntity(entity);
            } else {
                iResult = iLoanUserService.InsertLoanUser(entity);
            }
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/add_loanusertj")
    public ExceResult AddLoanUserTj(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String struserid = request.getParameter("userid");
            String strstatus = request.getParameter("status");
            String strloanid = request.getParameter("loanid");

            String loandes = "";

            int status = Integer.parseInt(strstatus);
            Long userid = Long.parseLong(struserid);
            Long loanid = Long.parseLong(strloanid);


            int iResult = 0;
            iResult = iLoanUserService.UpdateLoanUser(loanid, 0L, loandes, status, userid, this.GetLoginUserId());
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @RequestMapping(value = "/add_loanusergd")
    public String AddLoanUserGd(HttpServletRequest request, HttpServletResponse response) {
        try {
            String struserid = request.getParameter("userid");
            String strstatus = request.getParameter("status");
            String strloanid = request.getParameter("loanid");
            String strloanorgid = request.getParameter("loanorgid");

            String loandes = request.getParameter("loandes");

            int status = Integer.parseInt(strstatus);
            Long userid = Long.parseLong(struserid);
            Long loanid = Long.parseLong(strloanid);
            Long loanorgid = Long.parseLong(strloanorgid);
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            loandes = "<br/>" + sdf.format(d) + " " + loandes;
            int iResult = 0;

            iResult = iLoanUserService.UpdateLoanUser(loanid, loanorgid, loandes, status, userid, this.GetLoginUserId());
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @RequestMapping(value = "/add_loanuserjs")
    public String AddLoanUserJs(HttpServletRequest request, HttpServletResponse response) {
        try {
            String struserid = request.getParameter("userid");
            String strstatus = request.getParameter("status");
            String strloanid = request.getParameter("loanid");
            String strloanorgid = request.getParameter("loanorgid");


            String loandes = request.getParameter("loandes");

            int status = Integer.parseInt(strstatus);
            Long userid = Long.parseLong(struserid);
            Long loanid = Long.parseLong(strloanid);
            Long loanorgid = Long.parseLong(strloanorgid);


            int iResult = 0;
            iResult = iLoanUserService.UpdateLoanUserJs(loanid, loandes, status, userid, this.GetLoginUserId(), loanorgid);
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<LoanUserListEntity> GetList(HttpServletRequest request) {

        List<LoanUserListEntity> lst = null;
        LayTable<LoanUserListEntity> layTable = new LayTable<LoanUserListEntity>();
        try {
            String year = request.getParameter("year");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String where = "";
            String orgs = "";
            if (year != null && year.length() > 0) {
                where += " AND createtime>='" + year + "-01-01 00:00:00' AND createtime<='" + year + "-12-31 23:59:59' ";
            }

            if (orgid != null && orgid.length() > 0) {
//				OrgEntity orgentity=iOrgService.GetOrgById(Long.parseLong(orgid));
//				where+=" AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>="+orgentity.getLft()+" AND lft<="+orgentity.getRgt()+"))";
                List<OrgEntity> orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));
                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }
            }

            if (this.GetOrgListByRole() != "") {
                where += " AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN (" + this.GetOrgListByRole() + ") OR rsgxszdw IN (" + this.GetOrgListByRole() + "))";
            }

            if (orgs.length() > 0) {
                where += " AND szdw in (" + orgs + ")";
            }

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;

            lst = iLoanUserService.GetUserLoanList(wherelimit, realname);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iLoanUserService.GetUserLoanListCount(where, realname);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_gd_list")
    public LayTable<LoanUserListEntity> GetGdList(HttpServletRequest request) {

        List<LoanUserListEntity> lst = null;
        LayTable<LoanUserListEntity> layTable = new LayTable<LoanUserListEntity>();
        try {
            String year = request.getParameter("year");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String where = "  ";//AND status IN (0,1,2,3)
            String orgs = "";
            if (year != null && year.length() > 0) {
                where += " AND createtime>='" + year + "-01-01 00:00:00' AND createtime<='" + year + "-12-31 23:59:59' ";
            }

            if (orgid != null && orgid.length() > 0) {
//				OrgEntity orgentity=iOrgService.GetOrgById(Long.parseLong(orgid));
//				where+=" AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>="+orgentity.getLft()+" AND lft<="+orgentity.getRgt()+"))";
                List<OrgEntity> orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));
                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }

                if (orgs.length() > 0) {
                    where += " AND szdw in (" + orgs + ")";
                }

            }

            if (this.GetOrgListByRole() != "") {
//				where+= " AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN ("+this.GetOrgListByRole()+") OR rsgxszdw IN ("+this.GetOrgListByRole()+"))";
                where += " AND  szdw IN (" + this.GetOrgListByRole() + ") OR rsgxszdw IN (" + this.GetOrgListByRole() + ")";
            }

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;

            lst = iLoanUserService.GetUserLoanList(wherelimit, realname);


            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);

                if (lst.get(i).getLoandes() != null) {

                    String loandes = lst.get(i).getLoandes();
                    if (loandes.length() > 5) {

                        char first = loandes.charAt(0);

                        if (String.valueOf(first).equals("<")) {
                            lst.get(i).setLoandes(loandes.substring(5, lst.get(i).getLoandes().length()));

                        }


                    }


                }
            }

            int iCount = iLoanUserService.GetUserLoanListCount(where, realname);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_js_list")
    public LayTable<LoanUserListEntity> GetJsList(HttpServletRequest request) {

        List<LoanUserListEntity> lst = null;
        LayTable<LoanUserListEntity> layTable = new LayTable<LoanUserListEntity>();
        try {
            String year = request.getParameter("year");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String dqflag = request.getParameter("dqflag");
            String orgs = "";

            String where = "  ";//AND status IN (1,3)
            if (year != null && year.length() > 0) {
                where += " AND createtime>='" + year + "-01-01 00:00:00' AND createtime<='" + year + "-12-31 23:59:59' ";
            }

            if (orgid != null && orgid.length() > 0) {
//				OrgEntity orgentity=iOrgService.GetOrgById(Long.parseLong(orgid));
//				where+=" AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>="+orgentity.getLft()+" AND lft<="+orgentity.getRgt()+"))";
                List<OrgEntity> orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));
                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }
                if (orgs.length() > 0) {
                    where += " AND szdw in (" + orgs + ")";
                }
            }


            if (this.GetOrgListByRole() != "") {
                where += " AND (szdw IN (" + this.GetOrgListByRole() + ") OR rsgxszdw IN (" + this.GetOrgListByRole() + ") OR loanorgid IN (" + this.GetOrgListByRole() + "))";
            }

            if (dqflag != null && dqflag.length() > 0 && dqflag.equals("1")) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                where += " AND endtime<='" + df.format(new Date()) + "' AND status=4 ";
            }

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;

            lst = iLoanUserService.GetUserLoanList(wherelimit, realname);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iLoanUserService.GetUserLoanListCount(where, realname);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/delete_loanuser")
    public ExceResult DeleteLoan(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long loanid = Long.parseLong(request.getParameter("loanid"));
            int iResult = iLoanUserService.DeleteUserLoan(loanid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    //固化0808
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list_ck")
    public LayTable<LoanUserListEntity> GetListCk(HttpServletRequest request) {

        List<LoanUserListEntity> lst = null;
        LayTable<LoanUserListEntity> layTable = new LayTable<LoanUserListEntity>();
        try {
            String year = request.getParameter("year");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String where = "";
            String orgs = "";
            if (year != null && year.length() > 0) {
                where += " AND createtime>='" + year + "-01-01 00:00:00' AND createtime<='" + year + "-12-31 23:59:59' ";
            }

            if (orgid != null && orgid.length() > 0) {
//				OrgEntity orgentity=iOrgService.GetOrgById(Long.parseLong(orgid));
//				where+=" AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>="+orgentity.getLft()+" AND lft<="+orgentity.getRgt()+"))";
                List<OrgEntity> orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));
                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }

                if (orgs.length() > 0) {
                    where += " AND szdw in (" + orgs + ")";
                }
            }

            if (this.GetOrgListByRole() != "") {
//				where+= " AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN ("+this.GetOrgListByRole()+") OR rsgxszdw IN ("+this.GetOrgListByRole()+"))";
                where += " AND szdw IN (" + this.GetOrgListByRole() + ") OR rsgxszdw IN (" + this.GetOrgListByRole() + ")";
            }

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;

            lst = iLoanUserService.GetUserLoanList(wherelimit, realname);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iLoanUserService.GetUserLoanListCount(where, realname);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }

}
